package com.thf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;


@Controller
public class LoginCaptchaController extends HttpServlet {

    public static final int WIDTH = 120;
    /**
     * 图片高度：50px
     */
    public static final int HEIGHT = 50;
    int x_offset = 5, y_offset = 28;
    private Random random = new Random();
    /**
     * 处理图片验证码方法
     *
     * @param req
     * @param resp
     */

    @RequestMapping("/login/captcha")
    public void loginCaptcha(HttpServletRequest req, HttpServletResponse resp){
        try {
            //创建字节数组输出流
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            //创建图片缓存对象,BufferedImage.TYPE_INT_RGB ： 表示一个图像，该图像具有整数像素的 8 位 RGB 颜色
            BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            //获取图片的画布
            Graphics2D graphics = bufferedImage.createGraphics();
            //设置画布背景色
            graphics.setColor(Color.LIGHT_GRAY);
            //设置画布填充区域
            graphics.fillRect(0, 0, WIDTH, HEIGHT);
            //为画布添加边框
            graphics.setColor(Color.LIGHT_GRAY);
            //边框区域
            graphics.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);//drawRect是绘制矩形边框
            //绘制干扰线
            for (int i = 0; i < 10; i++)
            {
                graphics.setColor(new Color(randNum(0, 255), randNum(0, 255), randNum(0, 255)));

                graphics.drawLine(randNum(0, WIDTH), randNum(0, HEIGHT), randNum(0, WIDTH), randNum(0, HEIGHT));

            }
            //设置字体样式
            graphics.setFont(new Font("微软雅黑", Font.ITALIC, 20));
            //生成6位随机验证码
            String captcha = this.getRandomCode(4,graphics);
            //将生成的验证码存放到session中
            req.getSession().setAttribute("captcha", captcha);

            ImageIO.write(bufferedImage, "jpeg", jpegOutputStream);
            byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
            //将验证码输出到页面
            resp.setHeader("Cache-Control", "no-store");
            resp.setHeader("Pragma", "no-cache");
            resp.setDateHeader("Expires", 0L);
            resp.setContentType("image/jpeg");
            ServletOutputStream respOs = resp.getOutputStream();
            respOs.write(captchaChallengeAsJpeg);
            respOs.flush();
            respOs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成0-9，a-z,A-Z的随机字符串
     * @param count
     * @return
     */
    private String getRandomCode(int count,Graphics2D graphics) {
        String[] array = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
        Color[] colors = { Color.BLACK, Color.RED, Color.BLUE ,Color.CYAN ,Color.GRAY , Color.GREEN ,Color.MAGENTA ,Color.ORANGE ,Color.PINK ,Color.RED ,Color.WHITE ,Color.YELLOW};
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < count; i++) {
            int r = randNum(-180, 180);
            //生成一个下标0-61之间一个整数
            int index = (int) Math.round(Math.random() * 61);
            //从array数组中获取该下标字符放到result中
            String code = array[index];
            graphics.rotate(r / 180 * Math.PI);
            //设置字体颜色
            graphics.setColor(colors[randNum(0, colors.length)]);
            //填充数据
            graphics.drawString(code, x_offset + i * 30, y_offset);
            graphics.rotate(-r / 180 * Math.PI);

            result.append(code);
        }
        return result.toString();
    }

    //随机生成begin和end之间的一个int值
    private int randNum(int begin, int end) {
        return random.nextInt(end - begin) + begin;
    }


}
